package com.yyzw.activiti.modeler.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyzw.activiti.modeler.dao.RoleMapper;
import com.yyzw.activiti.modeler.model.DataGridRespVo;
import com.yyzw.activiti.modeler.model.ResponseVo;
import com.yyzw.activiti.modeler.model.SysRole;
import com.yyzw.activiti.modeler.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public DataGridRespVo getSysRoleByPage(int page, int pageSize) {
        Example example =new Example(SysRole.class);
        List<SysRole> sysRoles = this.roleMapper.selectByExample(example);
        DataGridRespVo dataGridRespVo = new DataGridRespVo();
        PageHelper.startPage(page,pageSize);
        PageInfo<SysRole> pageInfo = new PageInfo<>(sysRoles);
        dataGridRespVo.setRows(sysRoles);
        dataGridRespVo.setTotal(pageInfo.getTotal());
        return dataGridRespVo;
    }

    @Override
    public int delRole(int roleId) {
        SysRole sysRole =new SysRole();
        sysRole.setRoleId(roleId);
        this.roleMapper.delMenuRole(roleId);
        return this.roleMapper.deleteByPrimaryKey(sysRole);
    }

    @Override
    public ResponseVo addRole(SysRole sysRole, List<String> menuIds) {
        try {
            this.roleMapper.insert(sysRole);
            int roleId = sysRole.getRoleId();
            for(int i=0;i<menuIds.size();i++){
                this.roleMapper.insertMenuRole(roleId,Integer.parseInt(menuIds.get(i)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseVo(false,"添加失败");
        }
        return new ResponseVo(true,"添加成功");
    }

    @Override
    public ResponseVo updateRole(SysRole sysRole, List<String> menuIds) {
        try {
            this.roleMapper.updateByPrimaryKey(sysRole);
            //删除原有的对应关系
            this.roleMapper.delMenuRole(sysRole.getRoleId());
            //新增对应关系
            for(int i=0;i<menuIds.size();i++){
                this.roleMapper.insertMenuRole(sysRole.getRoleId(),Integer.parseInt(menuIds.get(i)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseVo(false,"修改失败");
        }
        return new ResponseVo(true,"修改成功");
    }

    @Override
    public List<SysRole> getSYsRoleList() {
       return this.roleMapper.selectAll();
    }
}
